package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Comment;
import com.example.springboot.service.ICommentService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/comment")
public class CommentController {

    @Resource
    private ICommentService commentService;

//    //查询用户评论与其子数据数据
//    @GetMapping("/{channelId}")
//    public Result findAll(@PathVariable Integer channelId) {
//        return Result.success(commentService.findComments(channelId));
//    }


    @GetMapping("/tree/{channelId}")
    public Result findTree(@PathVariable Integer channelId) {
        List<Comment> articleComments = commentService.findCommentDetail(channelId);

        return Result.success(articleComments);
    }


    //新增和修改
    @PostMapping
    public Result save(@RequestBody Comment comment) {  //@RequestBody接收前端数据
        if (comment.getId() == null) {
            comment.setUserid(TokenUtils.getCurrentUser().getId());
            comment.setTime(DateUtil.now());

            /**没有pid与 OriginId 就是一级评论， pid也就是你回复用户的评论id, OriginId也就是在一级回复的id*/

            if (comment.getPid() != null) {   // 判断如果回复，进行处理
                Integer pid = comment.getPid();
                Comment pComment = commentService.getById(pid);
                if (pComment.getOriginId() != null) {  // 如果当前回复的父级有祖宗，那么就设置相同的祖宗
                    comment.setOriginId(pComment.getOriginId());
                } else {   // 否则就设置父级为当前回复的祖宗
                    comment.setOriginId(comment.getPid());
                }
            }
        }
        return Result.success(commentService.saveOrUpdate(comment));
    }

    //删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(commentService.removeById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {

        return Result.success(commentService.removeByIds(ids));
    }

    //分页查询Mybatis-plus的方式,模糊查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") Integer channelId) {

        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        if (channelId != null) {
            queryWrapper.eq("channel_id", channelId);
        }
        return Result.success(commentService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }
}
